﻿
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.UI;
using DG.Tweening;

public class XObjBase : MonoBehaviour
{

    protected string OnGetKey()
    {
        Debug.LogError("没实现OnGetKey方法");
        return null;
    }



    private bool _isDestroy = false;
    private Dictionary<UnityEngine.Object, int> _asset2count;//key是string，所以需要工程key是唯一，不能代表多个资源
    private int _cacheCount;
    protected virtual void Awake()
    {
        _asset2count = new Dictionary<UnityEngine.Object, int>();
    }
    protected virtual void Start()
    {

    }
    public void LoadAssetAsync<T>(string key, Action<T> callback) where T : UnityEngine.Object
    {
        LoadAssetAsyncInternal(key, callback);
    }

    private async void LoadAssetAsyncInternal<T>(string key, Action<T> callback) where T : UnityEngine.Object
    {
        var op = Addressables.LoadAssetAsync<T>(key);
        var asset = await op.Task;
        if (_isDestroy)
        {
            Debug.LogError("already destroy，so no callback exe:" + this?.name);
            Addressables.Release(asset);
            return;
        }
        if(!_asset2count.TryGetValue(asset, out _cacheCount))
        {
            _cacheCount = 0;
        }
        _asset2count[asset] = ++_cacheCount;
        callback?.Invoke(asset);
    }

    protected virtual void OnDestroy()
    {
        _isDestroy = true;
        Release();
    }

    private void Release()
    {
        foreach (var asset in _asset2count.Keys)
        {
            _cacheCount = _asset2count[asset];
            for (int i = 0; i < _cacheCount; i++)
            {
                Addressables.Release(asset);
            }
        }
    }

    protected virtual void OnEnable()
    {

    }

    protected virtual void OnDisable()
    {

    }

}
